package cn.chinaflame.pagodas.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.OrderComparator;

import java.util.Map;

/**
 * Created by json on 2015/7/11.
 */
@Aspect
public class WebHandleInterceptorAdvisor implements ApplicationContextAware {

    public static final String ERROR_PAGE = "error_page";
    private static final Logger LOG = LoggerFactory.getLogger(WebHandleInterceptorAdvisor.class);
    private WebHandleInterceptor[] interceptors;

    @Around("execution(* cn.chinaflame.pagodas..*API.*(..))")
    public Object aroundHandle(ProceedingJoinPoint joinPoint) throws Throwable {
        LOG.info("joinPoint: {}", joinPoint);
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        if (interceptors != null) {
            for (WebHandleInterceptor wmi : interceptors) {
                wmi.preHandle(ms);
            }
        }
        return joinPoint.proceed();
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        Map<?, WebHandleInterceptor> vr = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, WebHandleInterceptor.class, true, false);
        LOG.info("Interceptors: {}", vr);
        if (!vr.isEmpty()) {
            this.interceptors = new WebHandleInterceptor[vr.size()];
            vr.values().toArray(this.interceptors);
            OrderComparator.sort(this.interceptors);
        }
    }
}
